<template>
    <div class="el-upload-model">
        <el-upload class="upload-demo" 
            action="#"
            ref="upload"
            accept=".mp4"
            :disabled="false"
            :show-file-list="false"
            :http-request="handleUploadImg"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">
              点击上传
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <i class="done el-icon-success" v-if="is_done">视频上传成功</i>
            <div slot="tip" class="el-upload__tip">只能上传MP4文件，且视频大小控制在300MB以内</div>
        </el-upload>
        <div class="el-progress-grid">
            <el-progress class="el-progressbar" 
                type="line" 
                v-if="progressFlag"
                color="#67c23a"
                :percentage="progressPercent">
            </el-progress>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'uploadFlie',        
        props: ["carTypeId","is_done"],
        data () {
            return {
                videoName: '',
                progressFlag: false,
                progressPercent: 0,
                // is_done: false
            }
        },
        methods: {
        	// 截取上传文件后缀
            getSuffix(filename) {
                let pos = filename.lastIndexOf('.')
                let suffix = ''
                if (pos != -1) suffix = filename.substring(pos)
                return suffix
            },
            // 生成随机数
            randomString(len) {
                len = len || 32
                const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
                const maxPos = chars.length
                let pwd = ''
                for (let i = 0; i < len; i++) {
                    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
                }
                return pwd
            },
            beforeAvatarUpload(file) {
                // const isLt100M = file.size / 1024 / 1024 >= 5 && file.size / 1024 / 1024 <= 100;
                const isLt300M = file.size / 1024 / 1024 <= 300;
				if (["video/mp4"].indexOf(file.type) == -1) {
					this.$message.error("请上传正确的视频格式");
					return false
				}
				if (!isLt300M) {
					this.$message.error("上传视频大小不能超过300MB!");
					return false
				}
                return true
            },
            handleUploadImg(file) {
                this.$http.post(`/admin/yt_car/index.php?act=yt_car&op=uploadVideo`, {brand_id: this.carTypeId}).then((res) => {
                    if (res) {
                        let picName = this.randomString(10) + this.getSuffix(file.file.name)
                        let keyValue = res.dir + picName
                        //注意formData里append添加的键的大小写
                        let formData = new FormData()
                            formData.append('name', file.file.name) // 文件名称
                            formData.append('key', keyValue) // 存储在oss的文件路径
                            formData.append('OSSAccessKeyId', res.accessid) // //accessKeyId
                            formData.append('policy', res.policy) // policy
                            formData.append('callback', res.callback) //回调地址
                            formData.append('Signature', res.signature) //签名
                            formData.append('success_action_status', 200)
                            formData.append('file', file.file, file.file.name) // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可

                        this.progressFlag = true
                        this.$http.post(res.host, formData, {
                            headers: { 
                                'Content-Type': 'multipart/form-data'
                            },
                            // 图片上传进度
                            onUploadProgress: (progressEvent) => {
                                this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
                            }
                        }).then((rep) => {
                            console.log(rep);
                            if (rep.code === 200) {
                                this.videoName = rep.data.filename
                                this.$emit('uploadSuccess', this.videoName) //传值给父级
                                this.is_done = true
                                console.log('Uploaded successfully', rep)
                                if (this.progressPercent >= 100) {
                                    this.progressFlag = false
                                    setTimeout(() => {
                                        this.progressPercent = 0
                                    },1000)
                                }
                            }
                        }).catch((err) => {
                            console.log(err);
                        })
                    }
                }).catch((err) => {
                    console.log(err)
                })
            },
            handleAvatarSuccess(res, file) {
                this.videoName = URL.createObjectURL(file.raw)
            }
        }
    }
</script>

<style lang="scss" scoped>
.el-progress-grid{
    width:80%;
}
.done{
    display: inline-block;
    font-size: 15px;
    color: #00d600;
    vertical-align: middle;
    margin-left: 10px;
}
</style>